Public Class frmProgrammerTester

    Private m_Programming As Boolean = False

#Region "Private CLasses"
    Private Class ProgrammerStatus_Args
        Inherits System.EventArgs

        Private m_Status As _eStatus
        Private m_Test As _eTests


        Sub New(ByVal test As _eTests, ByVal status As _eStatus)
            m_Test = test
            m_Status = status
        End Sub

        Public ReadOnly Property Status() As _eStatus
            Get
                Return m_Status
            End Get
        End Property

        Public ReadOnly Property Test() As _eTests
            Get
                Return m_Test
            End Get
        End Property

    End Class

    Private Class Programmer

        Private bgw As System.ComponentModel.BackgroundWorker
        Private eventArgs As System.ComponentModel.DoWorkEventArgs

        Public Event Progress(ByVal sender As Object, ByVal e As Emergency_Args)
        Public Event Messages(ByVal sender As Object, ByVal e As Emergency_Args)
        Public Event Status(ByVal sender As Object, ByVal e As ProgrammerStatus_Args)

        Private m_serial As Integer
        Private m_From As _eTests
        Private m_board_name As String = "BikiR0M USB Interface"
        Private m_prog_name As String = "Bikirom USB Propgrammer"

        Public Sub New(ByVal SerialNo As Integer, Optional ByVal from As _eTests = _eTests.Programmer_USB_Connected)
            m_serial = SerialNo
            m_From = from
        End Sub

        Public Function Execute( _
         ByVal backGroundWorker As System.ComponentModel.BackgroundWorker, _
         ByVal e As System.ComponentModel.DoWorkEventArgs) As Boolean
            ' set the varialbes
            bgw = backGroundWorker
            eventArgs = e

            Dim logging_file As New IO.FileStream(String.Format("report\BK3.0 {0}.txt", m_serial), IO.FileMode.OpenOrCreate)
            logging_file.Seek(0, IO.SeekOrigin.End)
            Dim logging As New IO.StreamWriter(logging_file)
            Dim logging_mem As New IO.MemoryStream
            Dim logging_temp As New IO.StreamWriter(logging_mem)
            Dim logging_string As String = ""
            Dim bStatus As Boolean = True

            ' Write the Header information to the Log file
            logging_temp.WriteLine("Starting new Test/Programming")

            Try
                '----------------------------------------------------------------------------------------------------------------------------------------------------------------
                ' Program hte USB
                If bStatus Then
                    bStatus = test_programmer_present(m_serial, logging_temp)
                    If bStatus Then
                        RaiseEvent Status(Me, New ProgrammerStatus_Args(_eTests.Programmer_USB_Connected, _eStatus.eStatusDone))
                        RaiseEvent Status(Me, New ProgrammerStatus_Args(_eTests.DUT_Power_Enabled, _eStatus.eStatusDone))
                    End If
                End If

                logging_temp.Flush()
                RaiseEvent Messages(Me, New Emergency_Args(0, cv_StringFromBytes(logging_mem.ToArray)))
                If Me.bgw.CancellationPending Then
                    bStatus = False
                End If

                If m_From <> _eTests.Programmer_USB_Connected Then
                    Select Case m_From
                        Case _eTests.DUT_USB_Programmed, _eTests.DUT_USB_Connected
                            GoTo tst_Usb
                        Case _eTests.DUT_Bootloader_Programmed, _eTests.DUT_Firmware_Loaded
                            GoTo Tst_Boot
                        Case _eTests.DUT_Flash_Check
                            GoTo Tst_Flash
                        Case _eTests.DUT_Flash_Write_Read
                            GoTo Tst_Pattern
                    End Select
                End If

                '----------------------------------------------------------------------------------------------------------------------------------------------------------------
                ' Program the blank USB chip
tst_Usb:        If bStatus Then
                    bStatus = test_program_usb(m_serial, logging_temp)
                    If bStatus Then
                        RaiseEvent Status(Me, New ProgrammerStatus_Args(_eTests.DUT_USB_Programmed, _eStatus.eStatusDone))
                        RaiseEvent Status(Me, New ProgrammerStatus_Args(_eTests.DUT_USB_Connected, _eStatus.eStatusDone))
                    End If
                End If

                logging_temp.Flush()
                RaiseEvent Messages(Me, New Emergency_Args(0, cv_StringFromBytes(logging_mem.ToArray)))
                If Me.bgw.CancellationPending Then
                    bStatus = False
                End If

                '----------------------------------------------------------------------------------------------------------------------------------------------------------------
                ' Program the Atmel
Tst_Boot:       If bStatus Then
                    bStatus = test_program_bootloader(m_serial, logging_temp)
                    If bStatus Then
                        RaiseEvent Status(Me, New ProgrammerStatus_Args(_eTests.DUT_Bootloader_Programmed, _eStatus.eStatusDone))
                        RaiseEvent Status(Me, New ProgrammerStatus_Args(_eTests.DUT_Firmware_Loaded, _eStatus.eStatusDone))
                    End If
                End If

                logging_temp.Flush()
                RaiseEvent Messages(Me, New Emergency_Args(0, cv_StringFromBytes(logging_mem.ToArray)))
                If Me.bgw.CancellationPending Then
                    bStatus = False
                End If

                '----------------------------------------------------------------------------------------------------------------------------------------------------------------
                ' Test the flash banks
Tst_Flash:      If bStatus Then
                    bStatus = test_flash_banks(m_serial, logging_temp)
                    If bStatus Then
                        RaiseEvent Status(Me, New ProgrammerStatus_Args(_eTests.DUT_Flash_Check, _eStatus.eStatusDone))
                    End If
                End If

                logging_temp.Flush()
                RaiseEvent Messages(Me, New Emergency_Args(0, cv_StringFromBytes(logging_mem.ToArray)))
                If Me.bgw.CancellationPending Then
                    bStatus = False
                End If

                'GoTo skip
                '----------------------------------------------------------------------------------------------------------------------------------------------------------------
                ' Write the test pattern
Tst_Pattern:    If bStatus Then
                    bStatus = test_flash_write_pattern(m_serial, logging_temp)
                    If bStatus Then
                        RaiseEvent Status(Me, New ProgrammerStatus_Args(_eTests.DUT_Flash_Write_Read, _eStatus.eStatusDone))
                    End If
                End If

                logging_temp.Flush()
                RaiseEvent Messages(Me, New Emergency_Args(0, cv_StringFromBytes(logging_mem.ToArray)))
                If Me.bgw.CancellationPending Then
                    bStatus = False
                End If

                '-------------------
                ' ToDo: Remove the True
skip:           If BikiRom_Init(True, "Bikirom USB Propgrammer") = BK_return.BK_OK Then
                    Try
                        Dim frame As Comm.Comm_Frame
                        frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, , Comm_Frame.BikiFrameAction.DUT_DISABLE, , Comm.Comm_Frame.BikiFrameType.ID_LAST_COMMAND_STATUS)
                        frame.Send(, True)
                    Catch ex As Comm_Exceptions

                    End Try

                    close_bikirom()
                End If
            Catch ex As USB_exceptions

                logging_temp.WriteLine("A USB driver/connection issue occured. Check all USB connections and try again")
                logging_temp.Flush()
                RaiseEvent Messages(Me, New Emergency_Args(0, cv_StringFromBytes(logging_mem.ToArray)))

                bStatus = False
            End Try

EndFunc:

            '--------------------------------------------------------------------------------
            If bStatus Then
                RaiseEvent Status(Me, New ProgrammerStatus_Args(_eTests.eTestMAX, _eStatus.eStatusDone))
            Else
                RaiseEvent Status(Me, New ProgrammerStatus_Args(_eTests.eTestMAX, _eStatus.eStatusFailed))
            End If

            ' Write the Log file
            logging_temp.Flush()
            logging_mem.WriteTo(logging_file)
            logging_file.Flush()
            logging_file.Close()

        End Function

        Private Function run_test(ByRef logging As IO.StreamWriter, ByVal func As test_func, ByVal test As _eTests) As Boolean
            If func.Invoke(m_serial, logging) Then
                RaiseEvent Status(Me, New ProgrammerStatus_Args(test, _eStatus.eStatusTesting))
            End If
            logging.Flush()
        End Function

        Private Delegate Function test_func(ByVal nSerial As Integer, ByRef logging As IO.StreamWriter) As Boolean

#Region "Test Functions"
        Friend Function test_dut_enable(ByVal power As Boolean) As Boolean
            Try
                If True Or BikiRom_Init(True, "Bikirom USB Propgrammer") = BK_return.BK_OK Then
                    Try
                        Dim frame As Comm.Comm_Frame
                        If power Then
                            frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, , Comm_Frame.BikiFrameAction.DUT_ENABLE, , Comm.Comm_Frame.BikiFrameType.ID_LAST_COMMAND_STATUS)
                        Else
                            frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, , Comm_Frame.BikiFrameAction.DUT_DISABLE, , Comm.Comm_Frame.BikiFrameType.ID_LAST_COMMAND_STATUS)
                        End If

                        frame.Send(, True)
                    Catch ex As Comm_Exceptions

                    End Try

                    close_bikirom()
                End If
            Catch ex As Comm_Exceptions
                Return False
            Catch ex As USB_exceptions
                Return False
            End Try

            Return True
        End Function

        Friend Function test_flash_write_pattern(ByVal nSerial As Integer, ByRef logging As IO.StreamWriter) As Boolean
            Dim bStatus As Boolean = False
            logging.WriteLine("---------------------------------------------------------")
            logging.WriteLine("Test: Checking DUT Able to write pattern to Flash (Atmega1280 -> 29F800 x2")

            If BikiRom_Init(True, m_board_name) = BK_return.BK_OK Then
                Try
                    Dim frame As Comm.Comm_Frame

                    bStatus = True
                    BikiRom_Timeout(60000)

                    frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, , Comm_Frame.BikiFrameAction.RUN_ERASEBANK1, , Comm.Comm_Frame.BikiFrameType.ID_LAST_COMMAND_STATUS)
                    If frame.Send(, True, 3) <> Comm.Comm_Frame.BikiFrameResponse.CMD_OK Then
                        bStatus = False
                        logging.WriteLine("**********************************************************")
                        logging.WriteLine("* Flash Bank 1 Failed to erase                          **")
                        logging.WriteLine("* Check IC FlashBank1 (29F800)                          **")
                        logging.WriteLine("* Check IC Atmega1280                                   **")
                        logging.WriteLine("* Check IC 74CDT161212 U1,U4,U13,U14                    **")
                        logging.WriteLine("**********************************************************")
                    Else
                        logging.WriteLine("Result: Flash Bank 1 Erased OK")
                    End If

                    frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, , Comm_Frame.BikiFrameAction.RUN_ERASEBANK2, , Comm.Comm_Frame.BikiFrameType.ID_LAST_COMMAND_STATUS)
                    If frame.Send(, True, 3) <> Comm.Comm_Frame.BikiFrameResponse.CMD_OK Then
                        bStatus = False
                        logging.WriteLine("**********************************************************")
                        logging.WriteLine("* Flash Bank 1 Failed to erase                          **")
                        logging.WriteLine("* Check IC FlashBank1 (29F800)                          **")
                        logging.WriteLine("* Check IC Atmega1280                                   **")
                        logging.WriteLine("* Check IC 74CDT161212 U1,U4,U13,U14                    **")
                        logging.WriteLine("**********************************************************")
                    Else
                        logging.WriteLine("Result: Flash Bank 2 Erased OK")
                    End If

                    If bStatus Then

                        Threading.Thread.Sleep(100)

                        frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, , Comm_Frame.BikiFrameAction.RUN_TEST_WRITE_PATTERN, , Comm.Comm_Frame.BikiFrameType.ID_LAST_COMMAND_STATUS)
                        If frame.Send(, True, 3) <> Comm.Comm_Frame.BikiFrameResponse.CMD_PASSED Then
                            bStatus = False
                            logging.WriteLine("**********************************************************")
                            logging.WriteLine("* Flash Bank 1/2 Failed to write test pattern           **")
                            logging.WriteLine("* Check IC FlashBank1 + FlashBank2 (29F800)             **")
                            logging.WriteLine("* Check IC Atmega1280                                   **")
                            logging.WriteLine("* Check IC 74CDT161212 U1,U4,U13,U14                    **")
                            logging.WriteLine("**********************************************************")
                        Else
                            logging.WriteLine("Result: Flash Bank 1 + 2 Write Test Pattern OK")
                        End If
                    End If

                Catch ex As USB_exceptions
                    bStatus = False
                    logging.WriteLine("**********************************************************")
                    logging.WriteLine("* USB Communcation Error Occured during testing         **")
                    logging.WriteLine("**********************************************************")
                Catch ex As Comm_Exceptions
                    bStatus = False
                    logging.WriteLine("**********************************************************")
                    logging.WriteLine("* USB Communcation Error Occured during testing         **")
                    logging.WriteLine("**********************************************************")
                End Try

                If bStatus Then
                    logging.WriteLine("Result: Flash Bank 1+2 are OK!")
                End If

            Else
                logging.WriteLine("**********************************************************")
                logging.WriteLine("*Unable to initialise communications with DUT.          **")
                logging.WriteLine("*Check FT232R chip and usb connection to the DUT        **")
                logging.WriteLine("**********************************************************")

            End If

            close_bikirom()

            logging.WriteLine("---------------------------------------------------------")
            Return bStatus
        End Function


        Friend Function test_flash_banks(ByVal nSerial As Integer, ByRef logging As IO.StreamWriter) As Boolean
            Dim bStatus As Boolean = False
            logging.WriteLine("---------------------------------------------------------")
            logging.WriteLine("Test: Checking Flash Banks")

            If BikiRom_Init(True, m_board_name) = BK_return.BK_OK Then
                Try
                    Dim frame As Comm.Comm_Frame
                    bStatus = True

                    frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, , Comm_Frame.BikiFrameAction.RUN_DIAG_FLASH, , Comm.Comm_Frame.BikiFrameType.ID_LAST_COMMAND_STATUS)
                    If frame.Send(, True, 2) <> Comm.Comm_Frame.BikiFrameResponse.CMD_PASSED Then
                        bStatus = False
                        logging.WriteLine("**********************************************************")
                        logging.WriteLine("* Flash Bank 1 Failed to verify                         **")
                        logging.WriteLine("* Check IC FlashBank1 (29F800)                          **")
                        logging.WriteLine("**********************************************************")
                    End If

                    frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, , Comm_Frame.BikiFrameAction.RUN_DIAG_FLASH2, , Comm.Comm_Frame.BikiFrameType.ID_LAST_COMMAND_STATUS)
                    If frame.Send(, True, 2) <> Comm.Comm_Frame.BikiFrameResponse.CMD_PASSED Then
                        bStatus = False
                        logging.WriteLine("**********************************************************")
                        logging.WriteLine("* Flash Bank 1 Failed to verify                         **")
                        logging.WriteLine("* Check IC FlashBank2 (29F800)                          **")
                        logging.WriteLine("**********************************************************")
                    End If

                Catch ex As Comm_Exceptions
                    bStatus = False
                    logging.WriteLine("**********************************************************")
                    logging.WriteLine("* USB Communcation Error Occured during testing         **")
                    logging.WriteLine("**********************************************************")
                End Try

                If bStatus Then
                    logging.WriteLine("Result: Flash Bank 1+2 are OK!")
                End If
            Else
                logging.WriteLine("**********************************************************")
                logging.WriteLine("*Unable to initialise communications with DUT.          **")
                logging.WriteLine("*Check FT232R chip and usb connection to the DUT        **")
                logging.WriteLine("**********************************************************")
            End If

            close_bikirom()

            logging.WriteLine("---------------------------------------------------------")
            Return bStatus
        End Function

        Friend Function test_programmer_present(ByVal nSerial As Integer, ByRef logging As IO.StreamWriter) As Boolean
            Dim bStatus As Boolean = False
            logging.WriteLine("---------------------------------------------------------")
            logging.WriteLine("Test: Check for Programmed")

            ' ToDo: Remove the True
            If BikiRom_Init(True, "Bikirom USB Propgrammer") = BK_return.BK_OK Then
                logging.WriteLine("Result: Programmer Available")

                Try
                    Dim frame As Comm.Comm_Frame
                    frame = New Comm.Comm_Frame(Comm.Comm_Frame.BikiFrameType.ID_RUN_COMMAND, , Comm_Frame.BikiFrameAction.DUT_ENABLE, , Comm.Comm_Frame.BikiFrameType.ID_LAST_COMMAND_STATUS)
                    If frame.Send(, True, 3) = Comm.Comm_Frame.BikiFrameResponse.CMD_PASSED Then
                        logging.WriteLine("Result: Board Power Enabled")
                        bStatus = True
                    Else
                        bStatus = False
                    End If
                Catch ex As Comm_Exceptions
                    bStatus = False
                    logging.WriteLine("**********************************************************")
                    logging.WriteLine("* USB Communcation to Programmer during testing         **")
                    logging.WriteLine("**********************************************************")
                End Try
            Else
                logging.WriteLine("**********************************************************")
                logging.WriteLine("*Programmer not present. Check USB connect and try again**")
                logging.WriteLine("**********************************************************")
            End If

            close_bikirom()

            logging.WriteLine("---------------------------------------------------------")
            Return bStatus
        End Function
        Friend Function test_program_usb(ByVal nSerial As Integer, ByRef logging As IO.StreamWriter) As Boolean
            Dim usb_data As New FT_PROGRAM_DATA(0)
            Dim bStatus As Boolean = False
            Dim manu As New String(" ", 40)
            Dim manuid As New String(" ", 40)
            Dim desc As New String(" ", 40)
            Dim serial As New String(" ", 40)
            Dim timeout As Integer

            logging.WriteLine("---------------------------------------------------------")
            logging.WriteLine("Test: Program Blank USB device")


            If BikiRom_connect(, "BikiR0M USB Interface") = BK_return.BK_OK Then
                bStatus = True
                logging.WriteLine("Result: Device already programmed")

                close_bikirom()
            ElseIf BikiRom_connect(, "FT232R USB UART") = BK_return.BK_OK OrElse BikiRom_connect(, "USB Serial Converter") = BK_return.BK_OK Then
                bStatus = True

                If bStatus And FT_EraseEE(lngHandle) Then
                    bStatus = False
                End If

                If bStatus And FT_EE_ProgramEx(lngHandle, usb_data, usb_data.Manufacturer, usb_data.ManufacturerId, usb_data.Description, usb_data.SerialNumber) Then
                    bStatus = False
                End If

                If bStatus And FT_CyclePort(lngHandle) Then
                    logging.WriteLine("Result: Device programmed")
                    bStatus = False
                End If

                close_bikirom()

                If bStatus Then
                    timeout = 20
                    While BikiRom_connect(, "BikiR0M USB Interface") <> BK_return.BK_OK And timeout
                        Threading.Thread.Sleep(1000)
                        timeout -= 1
                    End While

                    If timeout = 0 Then
                        MsgBox("BikiRom USB Device wait timeout" & Chr(13) & "Wait for device driver to be installed and press OK to continue", MsgBoxStyle.Exclamation And MsgBoxStyle.OkOnly, "Device Driver Initialise Timeout")
                    End If

                    If BikiRom_connect(, "BikiR0M USB Interface") <> BK_return.BK_OK Then
                        bStatus = False
                    Else
                        bStatus = True
                    End If

                    close_bikirom()
                End If
            Else
                logging.WriteLine("**********************************************************")
                logging.WriteLine("*Blank USB Device not found! and blank board not present *")
                logging.WriteLine("*Check FT232R USB chip for connection                    *")
                logging.WriteLine("**********************************************************")
            End If

            close_bikirom()

            logging.WriteLine("---------------------------------------------------------")
            Return True
        End Function

        Friend Function test_program_bootloader(ByVal nSerial As Integer, ByRef logging As IO.StreamWriter) As Boolean
            logging.WriteLine("---------------------------------------------------------")
            logging.WriteLine("Test: Programming Bootloader/Firmware")
            logging.WriteLine("Serial Number: " & nSerial)
            Dim bStatus As Boolean = False
            Dim f_firm() As Byte = arrayLoad("data\BIKI_OS_1.0.12_33.bin")
            Dim f_boot() As Byte = arrayLoad("data\BIKIBOOT_V1.0_12_33.bin")
            Dim f_EEprom() As Byte = arrayLoad("data\eeprom.bin")

            If IsNothing(f_firm) Or IsNothing(f_boot) Or IsNothing(f_EEprom) Then
                Return False
            End If

            ' Save the serial number
            f_EEprom(12) = CByte(nSerial \ &H10000UI And &HFFUI)
            f_EEprom(13) = CByte(nSerial \ &H100UI And &HFFUI)
            f_EEprom(14) = CByte(nSerial And &HFFUI)

            logging.WriteLine("Random Bytes:")

            ' Write in the random bytes
            Dim rand As New Random()
            Dim f_BLoffset As Integer = 3952
            Dim f_EEoffset As Integer = 136
            Dim f_code(15) As Byte
            Dim f_count As Integer = 0
            Dim s As Integer
            For i As Integer = 1 To 8
                rand.NextBytes(f_code)
                logging.WriteLine("Code " & i & ": " & cv_HexFromBytes(f_code))
                f_count = 0
                For Each bit As Byte In f_code
                    'f_boot(f_BLoffset + f_count) = bit
                    f_EEprom(f_EEoffset - (f_count * 8)) = bit
                    f_count += 1
                Next
                f_BLoffset += 16
                f_EEoffset += 1
            Next

            'Dim Prog As New Program(BK_SPEEDS.BK_12MHz_V3)

            Dim Prog As New Program(BK_SPEEDS.BK_12MHz_V3, "Bikirom USB Propgrammer", "BikiR0M USB Interface")
            Prog.m_eeprom = f_EEprom
            Prog.m_flash = f_boot
            Prog.m_firmware = f_firm

            AddHandler Prog.Message, AddressOf program_event_handler
            AddHandler Prog.Progress, AddressOf program_event_handler

            If Prog.Execute(Nothing, Nothing) Then
                bStatus = True
                logging.WriteLine("!Programming Firmware Successful")
            Else
                bStatus = False
                logging.WriteLine("*Programming Firmware Failure")
            End If

            logging.WriteLine("---------------------------------------------------------")

            RemoveHandler Prog.Message, AddressOf program_event_handler
            RemoveHandler Prog.Progress, AddressOf program_event_handler

            Return bStatus
        End Function

        Private Sub program_event_handler(ByVal sender As Object, ByVal e As Emergency_Args)
            RaiseEvent Progress(Me, e)
        End Sub
#End Region

    End Class
#End Region

    Private Enum _eStatus As Byte
        eStatusNone
        eStatusTesting
        eStatusDone
        eStatusFailed
    End Enum

    Private Enum _eTests As Byte
        Programmer_USB_Connected
        DUT_USB_Programmed
        DUT_USB_Connected
        DUT_Power_Enabled
        DUT_Bootloader_Programmed
        DUT_Firmware_Loaded
        DUT_Flash_Check
        DUT_Flash_Write_Read
        DUT_Test_Outputs
        DUT_Check_ADC
        PROG_Read_Flash
        PROG_Check_ADC
        eTestMAX = PROG_Check_ADC
    End Enum

#Region "Helper Functions"
    Private Sub set_status(ByVal status As _eStatus)

        Select Case (status)
            Case _eStatus.eStatusDone
                uxStatus.Text = "Success"
                uxStatus.BackColor = Color.Green
                Me.uxSerial.Value = Me.uxSerial.Value + 1
            Case _eStatus.eStatusFailed
                uxStatus.Text = "Failed"
                uxStatus.BackColor = Color.Red
            Case _eStatus.eStatusNone
                uxStatus.Text = "Press GO"
                uxStatus.BackColor = Color.Beige
            Case _eStatus.eStatusTesting
                uxStatus.Text = "Testing"
                uxStatus.BackColor = Color.Yellow
        End Select
    End Sub

#End Region

#Region "Form Events"
    Private Sub frmProgrammerTester_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        set_status(_eStatus.eStatusNone)
    End Sub

    Private Sub uxBtnGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxBtnGo.Click
        If Not m_Programming Then
            Dim nSerial As Integer = uxSerial.Value

            set_status(_eStatus.eStatusTesting)

            ' Clear all checked
            Dim nCnt As Integer = 0
            While uxTestCheckList.CheckedItems.Count
                uxTestCheckList.SetItemChecked(nCnt, False)
                nCnt += 1
            End While

            m_Programming = True

            Dim prog As Programmer

            If uxCombo.SelectedIndex <> -1 Then
                prog = New Programmer(nSerial, uxCombo.SelectedIndex)
            Else
                prog = New Programmer(nSerial, _eTests.Programmer_USB_Connected)
            End If

            bwProgrammer.RunWorkerAsync(prog)
        End If
    End Sub
#End Region

#Region "Programmer Thread"
    Private Sub bwProgrammer_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwProgrammer.DoWork
        'This method will run on a thread other than the UI thread.
        'Be sure not to manipulate any Windows Forms controls created
        'on the UI thread from this method.
        Dim em As Programmer = CType(e.Argument, Programmer)
        AddHandler em.Messages, AddressOf bwProg_Messages
        AddHandler em.Progress, AddressOf bwProg_Progress
        AddHandler em.Status, AddressOf bwProg_Status

        em.Execute(bwProgrammer, e)
    End Sub
    Private Sub bwUpload_RunWorkerCompleted( _
        ByVal sender As Object, _
        ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
        Handles bwProgrammer.RunWorkerCompleted
        m_Programming = False
    End Sub

    Private Delegate Sub messages_callback(ByVal sender As System.Object, ByVal e As Emergency_Args)
    Private Delegate Sub status_callback(ByVal sender As System.Object, ByVal e As ProgrammerStatus_Args)

    Private Sub bwProg_Messages(ByVal sender As System.Object, ByVal e As Emergency_Args)
        If Me.InvokeRequired Then
            Me.Invoke(New messages_callback(AddressOf bwProg_Messages), New Object() {sender, e})
        Else
            Me.uxLogging.Lines = e.Message.Split(Chr(13))
        End If
    End Sub
    Private Sub bwProg_Progress(ByVal sender As System.Object, ByVal e As Emergency_Args)
        If Me.InvokeRequired Then
            Me.Invoke(New messages_callback(AddressOf bwProg_Progress), New Object() {sender, e})
        Else
            uxStatusTxt.Text = e.Message
            uxProgress.Value = e.Progress
        End If
    End Sub
    Private Sub bwProg_Status(ByVal sender As Object, ByVal e As ProgrammerStatus_Args)
        If Me.InvokeRequired Then
            Me.Invoke(New status_callback(AddressOf bwProg_Status), New Object() {sender, e})
        Else
            If e.Test = _eTests.eTestMAX Then
                set_status(e.Status)
            Else
                If e.Status = _eStatus.eStatusDone Then
                    Me.uxTestCheckList.SetItemChecked(e.Test, True)
                ElseIf e.Status = _eStatus.eStatusFailed Then
                    Me.uxTestCheckList.SetItemChecked(e.Test, False)
                End If
            End If
        End If
    End Sub
#End Region

    Private Sub uxDUTEnable_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles uxDUTEnable.CheckedChanged
        If Not m_Programming Then
            Dim nSerial As Integer = uxSerial.Value

            Dim prog As New Programmer(nSerial)

            prog.test_dut_enable(Me.uxDUTEnable.Checked)
        End If
    End Sub
End Class